package com.wl.dzt.sys.controller.fileupload;

import com.wl.dzt.sys.controller.param.Param;
import com.wl.dzt.sys.core.dao.DB;
import com.wl.dzt.sys.util.LogicUtil;
import com.wl.dzt.sys.util.ResourceUtils;
import com.wl.dzt.sys.util.WebUtils;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;



/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/11/011
 * @description 用于封装文件上传的模板和删除
 * 
 */
@Component
public class FileUploadTemplate {

	/**
	 * 文件最大值
	 */
	public static Long FILE_MAX_SIZE = 1024L * 1024 * 10;


	/**
	 * 文件上传路径
	 */
	private static Map<String, String> FILES_PATHS;

	static {
		FILES_PATHS = ResourceUtils.loadProperties("fileupload.properties");
	}

	/**
	 * <b>上传文件</b>
	 * <p>
	 * 根据文件上传配置项进行实体和文件的批量操作
	 * </p>
	 * 
	 * @param file
	 *            文件
	 * @param param
	 *            参数对象
	 * @return 是否上传成功
	 */
	public boolean upLoad(MultipartFile file, Param param) {
		Object entity = param.getEntity();
		BeanMap beanMap = BeanMap.create(entity);
		Class<?> clazz = entity.getClass();
		String key = clazz.getName() + "." + file.getName(), path = FILES_PATHS.get(key);
		long pre = System.currentTimeMillis();
		String rel = path + "/" + pre + "$$" + file.getOriginalFilename(), name = WebUtils.getWebRootPath(param.getRequest())
				+ "/" + rel;
		try {
			// 修改的时候如果重新上传了文件则删除掉原来的文件
			if (DB.exitId(entity) && !LogicUtil.empty(param.getId())) {
				Object old = DB.get(clazz, beanMap.get("id").toString(), file.getName());
				BeanMap oldMap = BeanMap.create(old);
				beanMap.put(file.getName(), oldMap.get(file.getName()));
				if (oldMap.get(file.getName()) != null) {
					String fpath = oldMap.get(file.getName()).toString();
					File deleteFile = new File(WebUtils.getWebRootPath(param.getRequest()) + "/" + fpath);
					if (deleteFile.exists()) {
						deleteFile.delete();
					}
				}
			}
			File newFile = new File(name);
			newFile.createNewFile();
			file.transferTo(newFile);
			beanMap.put(file.getName(), rel);
			return true;
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * <b>删除文件</b>
	 * <p>
	 * 如果存在配置项中就删除
	 * </p>
	 * 
	 * @param entity
	 * @param param
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public boolean delete(Object entity, Param param) {
		BeanMap beanMap = BeanMap.create(entity);
		Class<?> clazz = entity.getClass();
		beanMap.forEach((key, val) -> {
			String name = clazz.getName() + "." + key, path = FILES_PATHS.get(name);
			if (path != null) {
				File deleteFile = new File(WebUtils.getWebRootPath(param.getRequest()) + "/" + beanMap.get(key) + "");
				if (deleteFile.exists()) {
					deleteFile.delete();
				}
			}
		});
		return true;
	}

}
